package com.virus.mall.filter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.virus.mall.model.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Classname AdminFilter
 * @Description NULL
 * @Date 2021/4/16 22:44
 * @Created by virus
 */
@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {

    private ObjectMapper objectMapper = new ObjectMapper();

    {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "http://192.168.5.84:8085");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTION,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        if (!method.equals("OPTIONS")) {
            HttpSession session = request.getSession();
            String  email = (String) session.getAttribute("email");
            if (auth(requestURI)) {
                if (email == null) {
                    response.getWriter().println(objectMapper.writeValueAsString(Result.error("请先登录，可尝试先登出再登录")));
                    return;
                }
            }
        }
        chain.doFilter(req, resp);
    }

    private boolean auth(String requestURI) {
        return !requestURI.equals("/api/admin/admin/login") && !requestURI.equals("/api/admin/admin/logoutAdmin");
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
